package com.shirley.pers.zhufengfmvi.tasks;

import android.os.AsyncTask;
import android.support.annotation.NonNull;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.SoftReference;

/**
 * Description: 公共的异步任务的定义，主要处理接口回调的工作<br/>
 * <p/>
 * Copyright (c) , 2016, Shirley Xian <br/>
 * This program is protected by copyright laws. <br/>
 * ClassName: BaseTask<br/>
 * Date: 2016/4/6 15:14
 *
 * @author Shirley Xian
 * @version 1.0
 */
public abstract class BaseTask extends AsyncTask<String, Integer, TaskResult> {
    private SoftReference<TaskCallback> mSoftReference;

    public BaseTask(TaskCallback taskCallback) {
        mSoftReference = new SoftReference<>(taskCallback);
    }

    @Override
    protected void onPostExecute(TaskResult result) {
        super.onPostExecute(result);
        TaskCallback taskCallback = mSoftReference.get();
        if (taskCallback != null) {
            taskCallback.onTaskFinished(result);
        }
    }

    /**
     * 获取TaskResult实例，并设置属性,子类需要调用这个方法
     *
     * @param str    获取的服务器数据
     * @param result 空的TaskResult对象
     * @return TaskResult实例
     */
    protected TaskResult getTaskResult(String str, @NonNull TaskResult result) {
        if (str != null) {
            try {
                result.data = new JSONObject(str);
            } catch (JSONException e) {
                e.printStackTrace();
                result.state = 9;//9代表服务器数据解析异常
            }
        } else {
            result.state = 8;//8代表网络异常
        }
        return result;
    }
}
